package org.csu.mypetstore.api.service.impl;

import ch.qos.logback.core.subst.Token;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.Getter;
import org.csu.mypetstore.api.common.CommonResponce;
import org.csu.mypetstore.api.common.JwtTokenUtil;
import org.csu.mypetstore.api.entity.*;
import org.csu.mypetstore.api.persistence.*;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import org.csu.mypetstore.api.entity.Profile;

@Getter
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    BannerDataMapper bannerDataMapper;
    @Autowired
    LogMApper logMApper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ProfileMapper profileMApper;
    @Autowired
    private ProfileMapper profileMapper; // 注意拼写是否正确
    @Autowired
    SignonMapper signonMapper;
    @Autowired
    JwtTokenUtil jwTokenUtil;



    @Override
    public CommonResponce<Token> login(String username, String password){
        Account account=accountMapper.selectById(username);
        if (username.isEmpty()||password.isEmpty()){
            if (username.isEmpty()){
                return CommonResponce.createForError(1,"账号为空，请输入账号");
            }
            return CommonResponce.createForError(1,"密码为空，请输入密码");
        }
        if (account==null){
            return CommonResponce.createForError(1,"您还没有注册，请先注册账号");
        }
        String pwd=signonMapper.selectById(username).getPassword();
        if (!pwd.equals(password))
        {
            return CommonResponce.createForError(1,"密码错误，请重新输入密码");
        }
        String token=jwTokenUtil.generateToken(username);
        CommonResponce<Token>response=CommonResponce.createForSuccess();
        response.setData(account);
        response.put("token",token);
        return response;
    }

    @Override
    public CommonResponce register(AccountVO accountVO){
        Account existingUser = accountMapper.selectById(accountVO.getUsername());
        if (existingUser != null) {
            return CommonResponce.createForError(1, "用户名已经存在，请重新输入");
        }
        //判断逻辑
        Link_register(accountVO);
        accountVO.setMylistopt(0);
        accountVO.setBanneropt(0);

        accountVO.setPassword(DigestUtils.md5DigestAsHex(accountVO.getPassword().getBytes()));//加密
        Account account=new Account();
        Profile profile=new Profile();
        Signon signon=new Signon();
        splitAccountVO(accountVO,account,profile,signon);

        profileMapper.insert(profile);
        accountMapper.insert(account);
        signonMapper.insert(signon);
        return CommonResponce.createForSuccess("注册成功",accountVO);

    }

    @Override
    public CommonResponce<String> updateAccount(AccountVO account,String username){

        //username是原来的名字
        String userid=account.getUsername();
        if (userid==null)
        {
            return CommonResponce.createForError(1,"用户名为空，请重新输入");
        }
        if (accountMapper.selectById(userid)!=null) {
            return CommonResponce.createForError("你要修改的用户名已存在，请重新修改");
        }
        //执行更新
        UpdateTable(username,account);
        return CommonResponce.createForSuccessMessage("用户信息更改成功");
    }

    @Override
    public CommonResponce<AccountVO> getAccountInformation(String username){
        QueryWrapper<Account>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",username);
        queryWrapper.isEmptyOfEntity();
        Account testaccount=accountMapper.selectById(username);
        if (testaccount==null)
        {
            return CommonResponce.createForError("1,未查询到该用户");
        }
        Account account=new Account();
        Bannerdata bannerdata=new Bannerdata();
        Log log=new Log();
        Order order=new Order();
        Profile profile=new Profile();
        Signon signon=new Signon();
        AccountVO accountVO=new AccountVO();

        signon=signonMapper.selectById(username);
        account=accountMapper.selectById(username);
        profile= profileMapper.selectById(username);
//      accountVO=entityAccountVO(account,bannerdata,log,order,profile,signon);
        //显示基本信息即可
        accountVO=entityelementAccountVO(account,profile,signon);
        return CommonResponce.createForSuccess("获取用户信息成功",accountVO);
    }



    //登录验证
    @Override
   public CommonResponce<AccountVO>Signon(String username, String password) {

       QueryWrapper<Signon> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("username", username);
       //获取名字
       AccountVO accountVO = new AccountVO();
       Signon signon = signonMapper.selectById(username);
       if (username == null) {
           CommonResponce.createForError(1, "用户名为空");
       } else if (signon == null) {
           return CommonResponce.createForError(1, "当前账户未注册，请先注册");
       } else if (signon.getPassword() != password) {
           return CommonResponce.createForError(1, "用户名密码错误");
       } else {
           Account account = accountMapper.selectById(username);
           Bannerdata bannerdata = bannerDataMapper.selectById(username);
           Log log = logMApper.selectById(username);
           Order order = orderMapper.selectById(username);
           Profile profile = (Profile) profileMapper.selectById(username);
           entityAccountVO(account, bannerdata, log, order, profile, signon);
           return CommonResponce.createForSuccess("登陆成功", entityAccountVO(account, bannerdata, log, order, profile, signon));
       }
       return CommonResponce.createForError("未知错误");
   }

//    @Override
//    public CommonResponce<Object> success() {
//        CommonResponce.createForSuccessMessage("退出成功");
//        return null;
//    }
// AccountServiceImpl.java 修改
    public CommonResponce<Object> success() {

    return CommonResponce.createForSuccessMessage(0,"退出成功");
    }

    //发散
    // 将 AccountVO 的属性分配回原来的多个类中
    private void splitAccountVO(AccountVO accountVO, Account account,  Profile profile,Signon signon) {
        // 分配到 Account
        account.setUserid(accountVO.getUsername());
        account.setEmail(accountVO.getEmail());
        account.setFirstname(accountVO.getFirstname());
        account.setLastname(accountVO.getLastname());
        account.setStatus(accountVO.getStatus());
        account.setAddress1(accountVO.getAddress1());
        account.setAddress2(accountVO.getAddress2());
        account.setCity(accountVO.getCity());
        account.setState(accountVO.getState());
        account.setZip(accountVO.getZip());
        account.setCountry(accountVO.getCountry());
        account.setPhone(accountVO.getPhone());


        // 分配到 Profile
        profile.setUserid(accountVO.getUsername());
        profile.setLanguagePref(accountVO.getLanguagePref());
        profile.setFavoriteCategory(accountVO.getFavoriteCategory());
        profile.setMylistopt(accountVO.getMylistopt());
        profile.setBanneropt(accountVO.getBanneropt());

        //signon
        signon.setUsername(accountVO.getUsername());
        signon.setPassword(accountVO.getPassword());
    }

    //聚合
    private AccountVO entityAccountVO(Account account, Bannerdata bannerdatta, Log log, Order order, Profile profile, Signon signon){
        AccountVO accountVO=new AccountVO();

        accountVO.setUsername(account.getUserid());
        accountVO.setEmail(account.getEmail());
        accountVO.setFirstname(account.getFirstname());
        accountVO.setLastname(account.getLastname());
        accountVO.setStatus(account.getStatus());
        accountVO.setAddress1(account.getAddress1());
        accountVO.setAddress2(account.getAddress2());
        accountVO.setCity(account.getCity());
        accountVO.setState(account.getState());
        accountVO.setZip(account.getZip());
        accountVO.setCountry(account.getCountry());
        accountVO.setPhone(account.getPhone());


        accountVO.setFavoriteCategory(bannerdatta.getFavoriteCategory());
        accountVO.setBannername(bannerdatta.getBannername());


        accountVO.setLog_info(log.getLog_info());
        accountVO.setCreate_time(log.getCreate_time());


        accountVO.setOrderid(order.getOrderId());
        accountVO.setOrderdate(order.getOrderdate());
        accountVO.setShipaddr1(order.getShipaddr1());
        accountVO.setShipaddr2(order.getShipaddr2());
        accountVO.setShipcity(order.getShipcity());
        accountVO.setShipstate(order.getShipstate());
        accountVO.setShipzip(order.getShipzip());
        accountVO.setShipcountry(order.getShipcountry());
        accountVO.setBilladdr1(order.getBilladdr1());
        accountVO.setBilladdr2(order.getBilladdr2());
        accountVO.setBillcity(order.getBillcity());
        accountVO.setBillstate(order.getBillstate());
        accountVO.setShipzip(order.getBillzip());
        accountVO.setBillcountry(order.getBillcountry());
        accountVO.setCourier(order.getCourier());
        accountVO.setTotalprice(order.getTotalprice());
        accountVO.setBilltofirstname(order.getBilltofirstname());
        accountVO.setBilltolastname(order.getBilltolastname());
        accountVO.setShiptofirstname(order.getShiptofirstname());
        accountVO.setShiptolastname(order.getShiptolastname());
        accountVO.setCreditcard(order.getCreditcard());
        accountVO.setExprdate(order.getExprdate());
        accountVO.setCardtype(order.getCardtype());
        accountVO.setLocale(order.getLocale());


        accountVO.setLanguagePref(profile.getLanguagePref());
        accountVO.setFavoriteCategory(profile.getFavoriteCategory());
        accountVO.setMylistopt(profile.getMylistopt());
        accountVO.setBanneropt(profile.getBanneropt());

        accountVO.setPassword(signon.getPassword());

        return accountVO;
    }

    //整合基本信息，如果是，则将其写为“ ”。
    private AccountVO entityelementAccountVO(Account account,Profile profile, Signon signon){
        AccountVO accountVO=new AccountVO();

        accountVO.setUsername(account.getUserid());
        accountVO.setEmail(account.getEmail());
        accountVO.setFirstname(account.getFirstname());
        accountVO.setLastname(account.getLastname());
        accountVO.setStatus(account.getStatus());
        accountVO.setAddress1(account.getAddress1());
        accountVO.setAddress2(account.getAddress2());
        accountVO.setCity(account.getCity());
        accountVO.setState(account.getState());
        accountVO.setZip(account.getZip());
        accountVO.setCountry(account.getCountry());
        accountVO.setPhone(account.getPhone());

        accountVO.setLanguagePref(profile.getLanguagePref());
        accountVO.setFavoriteCategory(profile.getFavoriteCategory());
        accountVO.setMylistopt(profile.getMylistopt());
        accountVO.setBanneropt(profile.getBanneropt());

        accountVO.setPassword(signon.getPassword());

        return accountVO;
    }
    //更新函数
    private void UpdateTable(String username,AccountVO account)
    {
        //更新条件
        UpdateWrapper<Account> updateWrapper=new UpdateWrapper<>();
        UpdateWrapper<Signon>updateWrapper1=new UpdateWrapper<>();
        UpdateWrapper<Profile>updateWrapper2=new UpdateWrapper<>();
        UpdateWrapper<Log>updateWrapper3=new UpdateWrapper<>();
        updateWrapper.eq("userid",username);
        updateWrapper1.eq("username",username);
        updateWrapper2.eq("userid",username);
        //执行更新
        updateWrapper.set("userid",account.getUsername())
                .set("email", account.getEmail())
                .set("firstname", account.getFirstname())
                .set("lastname", account.getLastname())
                .set("status", account.getStatus())
                .set("addr1", account.getAddress1())
                .set("addr2", account.getAddress2())
                .set("city", account.getCity())
                .set("state", account.getState())
                .set("zip", account.getZip())
                .set("country", account.getCountry())
                .set("phone", account.getPhone());
        updateWrapper1.set("username",account.getUsername())
                .set("password",account.getPassword());
        updateWrapper2.set("userid",account.getUsername());
        updateWrapper3.set("username",account.getUsername())
                .eq("username",username);
        //检查siongonmapper
        int signonUpdateResult = signonMapper.update(null, updateWrapper1);
        if (signonUpdateResult <= 0) {
            // 打印错误日志或抛出异常
            CommonResponce.createForError(1,"siongon表更新失败");
        }
        accountMapper.update(null,updateWrapper);
        signonMapper.update(null, updateWrapper1);
        profileMapper.update(null,updateWrapper2);
    }

    //关联register()方法
    private CommonResponce Link_register(AccountVO accountVO)
    {
        if (accountVO.getUsername()==null) {
            return CommonResponce.createForError(1,"userid is can not be null");
        } else if (accountVO.getEmail()==null) {
            return CommonResponce.createForError(1,"email is can not be null");
        } else if (accountVO.getFirstname()==null) {
            return CommonResponce.createForError(1,"firstname is can not be null");
        }else if (accountVO.getLastname()==null) {
            return CommonResponce.createForError(1, "lastname is can not be null");
        }else if (accountVO.getStatus()==null) {
            return CommonResponce.createForError(1, "status is can not be null");
        } else if (accountVO.getAddress1()==null) {
            return CommonResponce.createForError(1, "addr1 is can not be null");
        } else if (accountVO.getAddress2()==null) {
            return CommonResponce.createForError(1, "addr2 is can not be null");
        }else if (accountVO.getCity()==null) {
            return CommonResponce.createForError(1, "city is can not be null");
        } else if (accountVO.getState()==null) {
            return CommonResponce.createForError(1, "state is can not be null");
        } else if (accountVO.getCountry()==null) {
            return CommonResponce.createForError(1, "country is can not be null");
        } else if (accountVO.getZip()==null) {
            return CommonResponce.createForError(1, "zip is can not be null");
        } else if (accountVO.getPhone()==null) {
            return CommonResponce.createForError(1, "phone is can not be null");
        } else if (accountVO.getFavoriteCategory()==null) {
            return CommonResponce.createForError(1, "favorite is can not be null");
        }
        return null;
    }
}
